'use strict';

const RouterService = require('../base');
const axios = require('axios');
const wxConfig = require("../../../config/wx.js");
class QualityInspectionService extends RouterService {
  static get modelName() {
    return 'Business.QualityInspection';
  }

  async create(payload) {
    await this.beforeCreate(payload);
    const res = await this.model.create({
      ...payload,
      create_time: new Date()
    });
    return res;
  }

  async getQrcode({ id }) {
    try {
      const res = await this.model.findByPk(id);
      if (!res) {
        throw new Error('质检单不存在');
      }
      if (res.qrcode) {
        return res.qrcode;
      }
      const tokenRes = await this.ctx.curl(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appid}&secret=${wxConfig.secret}`, { method: 'GET', dataType: 'json' });
      const token = tokenRes.data.access_token
      if (tokenRes.data.errcode) {
        throw new Error(tokenRes.data.errmsg);
      }
      const requestData = {
        path: `pages/scan/scan?id=${id}`,
        width: 430,
        env_version: 'trial',
      }
      const qcodeRes = await axios({
        // /wxa/getwxacode cgi-bin/wxaapp/createwxaqrcode
        url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${token}`,
        method: 'POST',
        data: requestData,
        responseType: 'arraybuffer',
      });
      const result = await this.ctx.service.common.upload.uploadCos(qcodeRes.data, new Date().getTime() + '.jpg')
      await this.model.update({
        qrcode: 'https://' + result.Location
      }, {
        where: {
          id: id
        }
      })
      return 'https://' + result.Location
    }
    catch (e) {
      console.log('e', e);
      throw new Error(e);
    }
  }
}

module.exports = QualityInspectionService;
